package com.itheima.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String pathInfo = request.getPathInfo().substring(1);
            Method method = this.getClass().getDeclaredMethod(pathInfo, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            Object result =method.invoke(this,request,response);
            objectMapper.writeValue(response.getOutputStream(),result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}